package com.sleep.psy.external_server.annotation;

import com.sleep.psy.external_server.annotation.entity.UserPermissionInfo;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 用户权限验证
 */
public class UserPermissionMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(UserPermissionInfo.class)
                && methodParameter.hasParameterAnnotation(UserPermission.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {
        UserPermissionInfo userPermissionInfo = (UserPermissionInfo) nativeWebRequest.getAttribute("userPermission", RequestAttributes.SCOPE_REQUEST);
        if (userPermissionInfo != null) {
            return userPermissionInfo;
        }
        throw new MissingServletRequestPartException("userPermission");
    }
}
